<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require 'config.php';

$user_id = $_SESSION['user_id'];

// 获取所有用户的帖子
$posts_per_page = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $posts_per_page;

$stmt = $conn->prepare("SELECT p.id, p.title, p.content, p.created_at, p.media, u.username, 
    (SELECT COUNT(*) FROM likes WHERE post_id = p.id) AS like_count,
    (SELECT COUNT(*) FROM likes WHERE post_id = p.id AND user_id = ?) AS user_liked
    FROM posts p 
    JOIN users u ON p.user_id = u.id 
    ORDER BY p.created_at DESC 
    LIMIT ?, ?");
$stmt->bind_param("iii", $user_id, $offset, $posts_per_page);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($post_id, $post_title, $post_content, $post_created_at, $post_media, $post_username, $like_count, $user_liked);

// 获取总帖子数
$total_posts_stmt = $conn->prepare("SELECT COUNT(*) FROM posts");
$total_posts_stmt->execute();
$total_posts_stmt->bind_result($total_posts);
$total_posts_stmt->fetch();
$total_pages = ceil($total_posts / $posts_per_page);

$total_posts_stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态流 - 论坛</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            background-image: url('https://images.unsplash.com/photo-1506748686214-e9df14d4d9d0');
            background-size: cover;
            background-position: center;
            color: #4c4948;
            font-family: 'Lato', Arial, sans-serif;
            margin: 0;
            display: flex;
            min-height: 100vh;
        }
        .overlay {
            background: rgba(255, 255, 255, 0.8);
            width: 100%;
            display: flex;
        }
        .sidebar {
            background-color: #2d3748;
            color: white;
            width: 250px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            border-radius: 15px;
            margin: 20px;
        }
        .sidebar a {
            color: white;
            display: block;
            padding: 10px 20px;
            margin: 10px 0;
            background: #3b4252;
            border-radius: 25px;
            transition: background 0.3s;
        }
        .sidebar a:hover {
            background: #a0aec0;
        }
        .main-content {
            flex: 1;
            padding: 20px;
            display: flex;
            flex-direction: column;
            margin: 20px;
            border-radius: 15px;
            background: #fff;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .bg-header {
            background-image: url('https://images.unsplash.com/photo-1542281286-9e0a16bb7366');
            background-size: cover;
            background-position: center;
            height: 200px;
            border-radius: 15px;
            position: relative;
            overflow: hidden;
        }
        .bg-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 0;
        }
        .bg-header h2 {
            position: relative;
            z-index: 1;
            color: white;
            text-align: center;
            line-height: 200px;
            font-size: 2rem;
            margin: 0;
        }
        .card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }
        .post-title a {
            color: #1a73e8;
            transition: color 0.3s;
        }
        .post-title a:hover {
            color: #0c4ea2;
        }
        .post-meta {
            font-size: 0.875rem;
            color: #6b7280;
            margin-top: 8px;
        }
        .media-content img,
        .media-content video,
        .media-content audio {
            max-width: 100%;
            height: auto;
            margin-top: 16px;
        }
        .post-actions {
            margin-top: 16px;
        }
        .like-btn {
            background: #1a73e8;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .like-btn:hover {
            background: #0c4ea2;
        }
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 8px;
        }
        .pagination a, .pagination span {
            padding: 8px 16px;
            background: #e2e8f0;
            border-radius: 5px;
            color: #4a5568;
            transition: background 0.3s;
        }
        .pagination a:hover {
            background: #cbd5e0;
        }
        .pagination .current-page {
            background: #1a73e8;
            color: white;
        }
    </style>
</head>
<body>
    <div class="overlay">
        <div class="sidebar">
            <h2 class="text-3xl font-bold mb-8">动态流</h2>
            <nav class="w-full">
                <a href="user/index.php" class="text-lg">我的主页</a>
                <a href="user/create_post.php" class="text-lg">发布新帖子</a>
                <a href="logout.php" class="text-lg text-red-500 hover:text-red-700">退出登录</a>
            </nav>
        </div>
        <div class="main-content">
            <div class="bg-header">
                <h2>动态流</h2>
            </div>
            <div class="card">
                <ul class="post-list space-y-8">
                    <?php
                    if ($stmt->num_rows > 0) {
                        while ($stmt->fetch()) {
                            echo "<li>
                                <div class='post-title text-xl font-semibold mb-2'><a href='user/view_post.php?id=$post_id'>" . htmlspecialchars($post_title) . "</a></div>
                                <div class='post-meta'>发布者: " . htmlspecialchars($post_username) . " | 发布时间: $post_created_at</div>
                                <div class='post-content mt-4'>" . nl2br(htmlspecialchars($post_content)) . "</div>";
                            if (!empty($post_media)) {
                                $media_type = mime_content_type($post_media);
                                if (strpos($media_type, 'image') !== false) {
                                    echo "<div class='media-content mt-4'><img src='$post_media' alt='图片'></div>";
                                } elseif (strpos($media_type, 'video') !== false) {
                                    echo "<div class='media-content mt-4'><video controls><source src='$post_media' type='$media_type'></video></div>";
                                } elseif (strpos($media_type, 'audio') !== false) {
                                    echo "<div class='media-content mt-4'><audio controls><source src='$post_media' type='$media_type'></audio></div>";
                                }
                            }
                            echo "<div class='post-actions mt-4'>
                                    <button class='like-btn' data-post-id='$post_id' data-action='" . ($user_liked ? 'unlike' : 'like') . "'>" . ($user_liked ? '取消点赞' : '点赞') . " ($like_count)</button>
                                  </div>
                            </li>";
                        }
                    } else {
                        echo "<li class='text-gray-500'>暂无帖子</li>";
                    }
                    $stmt->close();
                    $conn->close();
                    ?>
                </ul>
                <div class="pagination">
                    <?php
                    if ($total_pages > 1) {
                        for ($i = 1; $i <= $total_pages; $i++) {
                            if ($i == $page) {
                                echo "<span class='current-page'>$i</span>";
                            } else {
                                echo "<a href='feed.php?page=$i'>$i</a>";
                            }
                        }
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        $('.like-btn').on('click', function() {
            var button = $(this);
            var post_id = button.data('post-id');
            var action = button.data('action');

            $.ajax({
                url: 'like_post.php',
                type: 'POST',
                data: {
                    post_id: post_id,
                    action: action
                },
                success: function(response) {
                    var data = JSON.parse(response);
                    if (data.status === 'success') {
                        button.text((action === 'like' ? '取消点赞' : '点赞') + ' (' + data.like_count + ')');
                        button.data('action', action === 'like' ? 'unlike' : 'like');
                    } else {
                        alert(data.message);
                    }
                }
            });
        });
    });
    </script>
</body>
</html>